﻿using AutoMapper;
using MediatR;
using MES.Process.API.Application.Command.工序分类命令;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工序分类命令处理
{
    /// <summary>
    /// 工序分类编辑命令处理
    /// </summary>
    public class ProcessTypeEditCommandHandler : IRequestHandler<ProcessTypeEditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessType> typeRepository;
        private readonly ILogger<ProcessTypeEditCommandHandler> logger;
        private readonly IMapper mapper;
        public ProcessTypeEditCommandHandler(IBaseRepository<ProcessType> typeRepository, ILogger<ProcessTypeEditCommandHandler> logger = null, IMapper mapper = null)
        {
            this.typeRepository = typeRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(ProcessTypeEditCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model=mapper.Map<ProcessType>(request);
                if (request.IsUpdOrDel == false)
                {
                    var exists = await typeRepository.GetValues()
                        .AnyAsync(t => t.ID != request.Id && t.PTCode == request.PTCode, cancellationToken);
                    if (exists)
                    {
                        result.Code = APIEnums.Fail;
                        result.Message = "工序分类编号已存在";
                        return result;
                    }
                    result.Code = APIEnums.Success;
                    result.Message = "工序分类修改成功";
                    result.Data = await typeRepository.UpdateAsync(model);
                    logger.LogInformation("工序分类修改成功");
                    return result;

                }
                else 
                {
                    model.IsDelete=true;
                    result.Code = APIEnums.Success;
                    result.Message = "工序分类删除成功";
                    result.Data = await typeRepository.UpdateAsync(model);
                    logger.LogInformation("工序分类删除成功");
                    return result;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
